package itemlogdao

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"xr-game-server/core/cache"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/constants/db"
	"xr-game-server/dto/itemlogdto"
	"xr-game-server/entity"
)

var itemLogCache *cache.CacheMgr

func InitItemLogDao() {
	itemLogCache = cache.NewCacheMgr()
}

func GetItemLog(roleId uint64, max int) []*entity.ItemLog {
	ret := itemLogCache.GetData(roleId, func(ctx context.Context) (value interface{}, err error) {
		dbs := make([]*entity.ItemLog, common.Zero)
		g.Model(string(entity.TbItemLog)).Unscoped().Where(string(entity.ItemLogRoleId), roleId).Limit(max).OrderDesc(string(db.UpdatedAtName)).Scan(&dbs)
		return dbs, nil
	})
	return ret.([]*entity.ItemLog)
}

func AddItemLog(itemLog *entity.ItemLog, max int) {
	db := GetItemLog(itemLog.RoleId, max)
	db = append([]*entity.ItemLog{itemLog}, db...)
	itemLogCache.FlushCache(itemLog.RoleId, db)
}

func Page(req *itemlogdto.GetItemLogReq) (total int, data []*entity.ItemLog) {
	data = make([]*entity.ItemLog, common.Zero)
	whereMap := make(map[string]interface{})
	whereMap[string(entity.ItemLogRoleId)] = req.RoleId
	if req.SourceId != nil {
		whereMap[string(entity.ItemLogSourceId)] = req.SourceId
	}
	g.Model(string(entity.TbItemLog)).Unscoped().Where(string(entity.ItemLogRoleId), req.RoleId).Limit(req.PageIndex, req.PageSize).OrderDesc(string(db.UpdatedAtName)).ScanAndCount(&data, &total, false)
	return total, data
}
